import { useMemo, useState, useEffect } from 'react';
import { Drawer, message, Button, Table, Empty } from 'antd';
import moment from 'moment';
import { useInbizRouter } from '@inbiz/hooks';
import Pagination from '@inbiz/basic/Pagination';
import { getVersionData, processRelease } from '../server';
import './style.less';

export default function VersionManagement(props: any) {
    const { drawerParams, processKey } = props;
    const [versionData, setVersionData] = useState<any[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [total, setTotal] = useState<number>(0);
    const [pageIndex, setPageIndex] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(10);
    const history = useInbizRouter();

    const goViewVersion = (id: string) => {
        let _url = `${window.location.host}${window.location.pathname}${window.location.search}&processview=true${window.location.hash}`;
        window.open(_url);
    };

    const doRelease = (id: string) => {
        setLoading(true);
        processRelease(id, 'id').then((res) => {
            if (res?.code == '200') {
                getVersionData({ processKey, pageIndex, pageSize }).then((res) => {
                    if (res?.code == '200' && res?.details && res?.details?.rows && res?.details?.rows?.length) {
                        message.success({ content: res?.message, duration: .5 }).then(() => {
                            drawerParams?.onCancel && drawerParams?.onCancel();
                            let _url = `${window.location?.href?.split('?')?.[0]}?id=${res?.details?.rows?.[0]?.id}`;
                            window.open(_url, '_self');
                            window.location.reload();
                        })
                    } else {
                        message.error(res?.message);
                    };
                    setLoading(false);
                })
            } else {
                message.error(res?.message);
                setLoading(false);
            }
        }).catch((error) => {
            message.error(error);
            setLoading(false);
        })
    }

    const columns: any = useMemo(() => {
        return [
            {
                title: '序号',
                dataIndex: 'index',
                width: 50,
                ellipsis: true,
                render: (t: any, r: any, i: number) => i + 1,
            },
            {
                title: '流程名称',
                dataIndex: 'name',
                ellipsis: true,
            },
            {
                title: '版本',
                dataIndex: 'rev',
                width: 50,
                ellipsis: true,
                render: (t: number) => 'v' + t
            },
            {
                title: '发布人',
                dataIndex: 'publisher',
                width: 70,
                ellipsis: true,
            },
            {
                title: '提交时间',
                dataIndex: 'lastUpdateTime',
                width: 150,
                ellipsis: true,
                render: (t: string) => {
                    if (t) {
                        return moment(t).format('YYYY/MM/DD HH:mm:ss');
                    } else {
                        return '-'
                    }
                }
            },
            {
                title: '操作',
                dataIndex: 'opreatar',
                editable: true,
                width: 90,
                render: (t: any, r: any, i: number) => {
                    if (history?.location?.query?.id == r?.id || (versionData.every((item: any) => item?.id != history?.location?.query?.id) && i == 0 && pageIndex == 1)) {
                        return '当前版本'
                    } else {
                        return (
                            <>
                                <a style={{ marginRight: 10 }} onClick={() => { goViewVersion(r?.id) }}>查看</a>
                                <a onClick={() => { doRelease(r?.id) }}>发布</a>
                            </>
                        )
                    }
                },
                ellipsis: true,
            },
        ]
    }, [goViewVersion, history, doRelease, versionData, pageIndex]);

    const onPageChange = (page: { current: number, pageSize: number }) => {
        setPageIndex(page?.current);
        setPageSize(page?.pageSize);
        setLoading(true);
        getVersionData({ processKey, pageIndex: page?.current, pageSize: page?.pageSize }).then((res) => {
            if (res?.code == '200' && res?.details && res?.details?.rows && res?.details?.rows?.length) {
                setTotal(res?.details?.total);
                setVersionData(res?.details?.rows);
            } else {
                message.error(res?.message);
            };
            setLoading(false);
        }).catch((error) => {
            message.error(error);
            setLoading(false);
        })
    };

    const onCancel = () => {
        drawerParams?.onCancel && drawerParams?.onCancel();
    };

    useEffect(() => {
        setLoading(true);
        getVersionData({ processKey, pageIndex: 1, pageSize: 10 }).then((res) => {
            if (res?.code == '200' && res?.details && res?.details?.rows && res?.details?.rows?.length) {
                setTotal(res?.details?.total);
                setVersionData(res?.details?.rows);
            }
            setLoading(false);
        }).catch((error) => {
            message.error(error);
            setLoading(false);
        })
    }, []);

    return (
        <Drawer
            {...drawerParams}
            title='版本管理'
            bodyStyle={{
                height: '100%',
                padding: '20px 20px 0 20px',
            }}
        >
            <div className='process-designer-version-management'>
                <>
                    <div className='process-designer-version-management-table'>
                        <>
                            <Table
                                columns={columns}
                                dataSource={versionData}
                                pagination={false}
                                size="small"
                                rowKey="id"
                                bordered
                                loading={loading}
                                locale={{
                                    emptyText: (
                                        <Empty
                                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                                            description={'暂无数据'}
                                        />
                                    ),
                                }}
                            />
                            <Pagination
                                size='small'
                                options={[10, 20, 30, 40, 50]}
                                total={total}
                                current={pageIndex}
                                pageSize={pageSize}
                                onChange={onPageChange}
                                style={{ marginTop: 4, marginBottom: 4 }}
                            />
                        </>
                    </div>
                    <div className='process-designer-version-management-footer'>
                        <div>
                            <Button onClick={onCancel}>取消</Button>
                            <Button type='primary' onClick={onCancel}>确定</Button>
                        </div>
                    </div>
                </>
            </div>
        </Drawer>
    );
};